<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="[fee_ele, fld_cod]"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :type="col.type"
                :formatter="col.formatter"
                :sortable="col.sortable"
            >
                
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary" :icon="Plus" @click="add"
            >增加</el-button
        >
        <el-button class="btn" type="primary" :icon="Delete" @click="onDelete"
            >删除</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="计费模式元素维护"
        draggable
        destroy-on-close
        :center="true"
    >
        <NormalSysForm
            :formOptions="formOptions"
            :formItems="formItems"
            :formData="paramData"
            :createActionName="createActionName"
            :updateActionName="updateActionName"
            :rules="rules"
            @create="onAdded"
            @update="onUpdated"
            
        >
        </NormalSysForm>
    </el-dialog>
</template>
<script setup lang="ts" name="FeeModEles">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox, ElTable, FormRules } from 'element-plus';
import { Delete, Plus } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    forEachRight,
    
    findIndex,
    omit,
} from 'lodash';
import NormalSysForm from '@/components/forms/NormalSysForm.vue';

import type { FeeModEleModel, FeeModModel } from '@/common/types/business';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { FormFieldItem, SelectOption, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import { initObjectProperty, pickFormFromTable, transFormatter } from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
import { useFeeStore } from '@/store/fee';
const { eles } = storeToRefs(useFeeStore());
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<FeeModEleModel>>([]);
const paramData = reactive<FeeModEleModel>({});
const tableHeight = ref(100);
const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const props = defineProps<{
    data?: FeeModModel;
}>();
const emit = defineEmits<{
    'close': [];
}>();
const rules = reactive<FormRules>({
    // fee_mod_cod: [{ required: true, message: '请输入计费模式', trigger: 'blur' }],
    fee_ele: [{ required: true, message: '请输入计费元素', trigger: 'blur' }],
});
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: {value: string | number, label: string}[];
    if (column['property'] === 'fee_ele') {
        data = eles.value;
    } else {
        return cellValue;
    }
    return transFormatter(cellValue, data);
}

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fee_ele',
        label: '计费元素代码',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: eles.value,
        
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'fee_ele_seq',
        label: '计费元素排序',
        sortable: 'custom',
        formFieldItemType: 'number',
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
    },
]);
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);
const createActionName = ref('计费模式元素增加');
const updateActionName = ref('计费模式元素修改');

const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
let queryWhere = {
    where: {
        fee_mod_cod: {
            equals: props.data?.fee_mod_cod,
        },
    },
};

const onRefresh = async () => {
    // console.log('参数', paramData);

    const req = new Request('计费模式元素查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    onRefresh();
    tableHeight.value =
        window.innerHeight -
        Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom) +
        tableMaxHeightAdjust;
    // alert(tableHeight.value);
});
const add = () => {
    initObjectProperty(paramData);
    paramData.fee_mod_cod = props.data?.fee_mod_cod;
    dialogUpdateVisible.value = true;
};
const update = (row: FeeModEleModel) => {
    Object.assign(paramData, row, {
        primary_cod: { fee_mod_cod: row['fee_mod_cod'], fee_ele: row['fee_ele'] },
    });
    dialogUpdateVisible.value = true;
};
const onAdded = (data: FeeModEleModel) => {
    tableData.value.unshift(data);
};

const onUpdated = (data: FeeModEleModel) => {
    const i = findIndex(tableData.value, (o) => {
        return (
            o.fee_mod_cod === data.primary_cod.fee_mod_cod &&
            o.fee_mod_cod === data.primary_cod.fee_ele
        );
    });
    if (i > -1) {
        Object.assign(tableData.value[i], omit(data, ['primary_cod']));
    } else {
        ElMessage.error('修改失败');
    }
};
const onCloseDialog = async (arg: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};

const onDelete = async () => {
    const rows: Array<FeeModEleModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<{ fee_mod_cod: string; fee_ele: string }>();
    const labels = Array<string>();
    forEach(rows, (v: FeeModEleModel) => {
        ids.push({ fee_mod_cod: v.fee_mod_cod!, fee_ele: v.fee_ele! });
        labels.push(v.fee_ele as string);
    });

    const msg = labels.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下计费模式元素值', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('计费模式元素删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: FeeModEleModel, i: number) => {
                if (findIndex(ids, (val: { fee_mod_cod: string, fee_ele: string }) => {
                    return val.fee_mod_cod === v.fee_mod_cod && val.fee_ele === v.fee_ele;
                }) > -1) {
                    tableData.value.splice(i, 1);
                }
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
